// miniprogram/pages/homemates/homemates.js
import {
  wxp
} from '../../util/wxp'
const db = wx.cloud.database()
const _ = db.command

Page({

  /**
   * 页面的初始数据
   */
  data: {
    homemates: [],
    from: null
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.updateData()
    this.setData({
      'from': options.from
    })
  },
  async updateData() {
    const {
      data
    } = await db.collection('homemate').where({
      '_openid': getApp().globalData.openId,
      deleted: _.neq(1)
    }).get()
    this.setData({
      homemates: data
    })
  },
  getPrevPage() {
    const pages = getCurrentPages();
    const prevPage = pages[pages.length - 2]; //上一个页面     
    return prevPage
  },
  onSelectHomemate(e) {
    const index = e.currentTarget.dataset.index
    const homemate = this.data.homemates[index]
    if (this.data.from == 'record') {
      this.getPrevPage().setData({
        homemate
      })
      wx.navigateBack({
        url: `/pages/record/record`,
      })
    } else {
      wx.navigateTo({
        url: `/pages/homemates/homemate/homemate?_id=${homemate._id}`,
      })
    }
  },
  addHomemate: function () {
    wx.navigateTo({
      url: `/pages/homemates/homemate/homemate`,
    })
  }
})